import axios from 'axios'
axios.defaults.withCredentials = true;
import { Message, MessageBox, Notification, Loading } from 'element-ui'
import { getToken, setToken, removeToken } from '@/store/getters'
//  定义loading变量
var loading
// 使用Element loading-start 方法
function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中……',
    // spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.1)',
    target: document.querySelector('.loadingtext')

  })
}
// 使用Element loading-close 方法
function endLoading () {
  loading.close()
}

let needLoadingRequestCount = 0
export function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()

    setTimeout(
      function () {
        endLoading()
      }, 30000)
  }
  needLoadingRequestCount++
}

export function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.API_URL, // api的base_url
  timeout: 30000 // request timeout

})

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  config.headers.Authorization = getToken(); // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  showFullScreenLoading();

  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
     * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
     * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
     */
    const res = response.data
    tryHideFullScreenLoading()
    if (res.code == 5544) {
      if (res.data == 'token:login_again') {
        Message({
          message: '登录超时，请重新登录！',
          type: 'error',
          duration: 3 * 1000
        })
        removeToken();
        setTimeout(()=>{
          parent.location.href ='/';
        },2000)
        return Promise.reject('error')
      } else if (res.data == 'token:null_token') {
        Message({
          message: '请重新登录！',
          type: 'error',
          duration: 3 * 1000
        });
        setTimeout(()=>{
          parent.location.href ='/';
        },2000)
        return Promise.reject('error')
      } else if (res.data == 'token:error') {
        Message({
          message: 'token错误！',
          type: 'error',
          duration: 3 * 1000
        });
        removeToken();
        setTimeout(()=>{
          parent.location.href ='/';
        },2000)
        return Promise.reject ('error')
      }

    }
    if (response.status !== 200) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      return response.data
    }
  },
  error => {
    tryHideFullScreenLoading()
    console.log('err' + error) // for debug
    const response = error.response
    if (response === undefined) {
      Message({
        message: '服务请求超时！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    if (response.status === 400) {
      Message({
        message: '账户或密码错误！',
        type: 'warning'
      })
      return Promise.reject ('error')
    }
    const info = response.data
    // if (response.status === 401 && info.status === 40101) {
    //
    //   MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
    //     confirmButtonText: '重新登录',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     store.dispatch('LogOut').then(() => {
    //       location.reload() // 为了重新实例化vue-router对象 避免bug
    //     })
    //   })
    // }
    if (response.status === 401 && info.status === 40001) {
      Notification.warning({
        title: '禁止',
        message: info.message,
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject ('error')
    }
    if (response.status === 403) {
      Notification.warning({
        title: '禁止',
        message: info.message,
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject ('error')
    }
    if (info.status === 30101) {
      Notification.warning({
        title: '失败',
        message: info.message,
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject ('error')
    }
    if (response.status === 504) {
      Message({
        message: '后端服务异常，请联系管理员！',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    }
    Message({
      message: info.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
